﻿using Basic.FlowApplication.Model;
using Basic.FlowApplication.Model.AuditLog;
using Basic.FlowCollect;
using Basic.FlowModel.AuditLogItem;
using Basic.FlowModel.EventTemplate;
using Basic.FlowRemoteModel;
using WeDonekRpc.Client.Interface;
using WeDonekRpc.Helper;

namespace Basic.FlowApplication.AuditLocalEvent.AuditEvent
{
    internal class AuditLogEvent : IEventHandler<FlowAuditEvent>
    {
        private readonly IEventTemplateCollect _EventTemplate;

        public AuditLogEvent ( IEventTemplateCollect eventTemplate )
        {
            this._EventTemplate = eventTemplate;
        }

        public void HandleEvent ( FlowAuditEvent data, string eventName )
        {
            FlowEventType? evType = this._GetEventType(data);
            if ( evType.HasValue )
            {
                FlowNode begin = data.Flow.Nodes[data.Flow.BeginNode];
                if ( begin.MsgEvent.TryGetValue(evType.Value, out long evId) )
                {
                    EventDto temp = this._EventTemplate.GetEvent(evId);
                    this._Send(temp, data.Log, data.ItemId, evType.Value);
                }
            }
        }
        private void _Send ( EventDto eve, AuditLog log, long itemId, FlowEventType eventType )
        {
            AuditItemInfo item = log.Items.Find(a => a.Id == itemId);
            try
            {
                eve.Send(item, log, eventType);
            }
            catch ( Exception e )
            {
                ErrorException error = ErrorException.FormatError(e);
                error.SaveLog("FlowInter");
            }
        }
        private FlowEventType? _GetEventType ( FlowAuditEvent data )
        {
            if ( data.OldLogStatus == FlowAuditLogStatus.待开始 && data.Log.Status == FlowAuditLogStatus.进行中 )
            {
                return FlowEventType.审核开始;
            }
            else if ( data.Log.Status == FlowAuditLogStatus.已结束 )
            {
                return FlowEventType.审核结束;
            }
            return null;
        }
    }
}
